package com.why.config;

import com.why.cache.BeanCache;
import com.why.util.StringUtil;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.IOException;

public class FreeMarkerTemplateConfig {
    private static FreeMarkerTemplateConfig freeMarkerTemplateConfig;

    private FreeMarkerTemplateConfig(String backPackagePath) {
        buildTemplatesPath(backPackagePath);
    }

    public static FreeMarkerTemplateConfig getInstance() {
        GeneratorConfig generatorConfig = BeanCache.getBean("GeneratorConfig", GeneratorConfig.class);
        String backPackagePath = generatorConfig == null || StringUtil.isEmpty(generatorConfig.getFreeMarkPath())
                ? "/templates" : generatorConfig.getFreeMarkPath();
        if (BeanCache.getBean("FreeMarkerTemplateConfig", FreeMarkerTemplateConfig.class) == null) {
            BeanCache.putBean("FreeMarkerTemplateConfig", new FreeMarkerTemplateConfig(backPackagePath));
        }
        return BeanCache.getBean("FreeMarkerTemplateConfig", FreeMarkerTemplateConfig.class);
    }

    private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22);

//    static{
//        //这里比较重要，用来指定加载模板所在的路径
//        CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(FreeMarkerTemplateUtils.class, "/templates"));
//        CONFIGURATION.setDefaultEncoding("UTF-8");
//        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
//        CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
//    }

    public Template getTemplate(String templateName) throws IOException {
        try {
            return CONFIGURATION.getTemplate(templateName);
        } catch (IOException e) {
            throw e;
        }
    }

    private static void buildTemplatesPath(String backPackagePath) {
        CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(FreeMarkerTemplateConfig.class, backPackagePath));
        CONFIGURATION.setDefaultEncoding("UTF-8");
        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
    }

}
